This tutorial shows how to create custom .layout Modifier .myModifier(addHeight: Int) which increases View's height.
myModifier() is implemented as extension function to Modifier Class.
This is done by calling Modifier.layout which takes two parameters
● measurable is Composable to which Modifier is applied
● constraints imposed by the Parent (min/max width/height of child. Think of max values as the size of the Parent)
This is done in three steps
● first we measure Composable which returns Placeable containing the size of the Composable (depends on the text)
● then we call layout(width, height) to specify new size of the Composable
● and inside it we call placeable.placeRelative(x, y) to specify Composable position inside the this new layout size
We use Column to see how Text size was increased since .border isn't properly applied.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.setContent
import androidx.compose.ui.unit.dp
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Column {
Text("Hi there!", Modifier.myModifier(100).border(2.dp, Color.Magenta))
Text("Hi there!")
}
}
}
}
//Extension Function
fun Modifier.myModifier(addHeight: Int) = Modifier.layout { measurable, constraints ->
Log.d("PRINT", constraints.toString())
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height + addHeight) { placeable.placeRelative(0, 20) }
}
Output